package cn.com.dhcc.turbo.web.controller.monitor;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.modulehandler.valuebean.BetweenValue;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.DTUtil;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.core.util.XstreamUtil;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.consts.AppConst;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.app.pub.core.tag.AppTagEl;
import cn.com.dhcc.turbo.entity.api.RouteLog;
import cn.com.dhcc.turbo.entity.exch.RecvFileData;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo.SL_AUTH_FLAG;
import cn.com.dhcc.turbo.service.exch.filedata.RecvFileDataService;
import cn.com.dhcc.turbo.service.registry.BaseInfoService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;

@Controller
@RequestMapping("/monitor")
@TurboMenu(belongToMenu = TurboMenu.LEAF_MENU.UNSTRUC_MONITOR_RECV)
public class RecvFileDataController extends BaseController {
    @SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.SAI);

    @Autowired
    private RecvFileDataService recvFileDataService;
    @Autowired
    private NodeInfoService nodeInfoService;
   
    @Autowired
    private BaseInfoService baseInfoService;
    @RequestMapping(value = "/recv_file_data_list")
    public String list(
            Model model,
            Pager pager,
            HttpServletRequest request,
            String sendNodecode,
            String sendAdaptercode,
            String recvNodecode,
            String sendStatus,
            String notifyStatus,
            String startCreated,
            String endCreated,
            String orderName,
            String order) {
        try {

            UserInfo userInfo = (UserInfo)BaseController.getCurrentUserInfo(request.getSession());
			boolean isSysUser = userInfo.getSlAuthFlag().equalsIgnoreCase(SL_AUTH_FLAG.SYS_USER.getCode());
			NodeInfo localNode=nodeInfoService.getLocalNode();
			List<Map<String,String>> recvNodeList=new ArrayList<Map<String,String>>();
			List<Map<String,String>> recvAdapterList=new ArrayList<Map<String,String>>();
			
            WhereCondition searchData = new WhereCondition();
            searchData.where().eq("1", "1");

            if (StrUtil.isNotBlank(notifyStatus)) {
				searchData.and().like("NOTIFY_STATUS", notifyStatus);
			}
            if (StrUtil.isNotBlank(sendNodecode)) {
                searchData.and().like("send_nodecode", sendNodecode);
            }
            if (StrUtil.isNotBlank(sendAdaptercode)) {
                searchData.and().like("send_adaptorcode", sendAdaptercode);
            }
            if (StrUtil.isNotBlank(recvNodecode)) {
                searchData.and().like("recv_nodecode", recvNodecode);
            }else if (isSysUser) {
				searchData.and().like("recv_nodecode", baseInfoService.getCurrentNodeInfo().getNodeCode());
				searchData.and().like("recv_adaptorcode", userInfo.getUserName());
				
				//默认选择项
				Map<String,String> recvNodeMap=new HashMap<String, String>();
				recvNodeMap.put("code", localNode.getNodeCode());
				recvNodeMap.put("name", localNode.getNodeName());
				recvNodeList.add(recvNodeMap);
				//默认选择项
				//默认选择项
				Map<String,String> recvAdapterMap=new HashMap<String, String>();
				recvAdapterMap.put("code", userInfo.getUserName());
				recvAdapterMap.put("name", AppTagEl.adaptorName(userInfo.getUserName()));
				recvAdapterList.add(recvAdapterMap);
			}
           
            if (StrUtil.isNotBlank(sendStatus)) {
                searchData.and().eq("send_status", sendStatus);
            }
            //时间范围从那天到那天
            //时间范围从那天到那天
            if (StrUtil.isNotBlank(startCreated) && StrUtil.isNotBlank(endCreated)) {
                searchData.and().between("modified", new BetweenValue(DTUtil.toDateTime(startCreated) , DTUtil.toDateTime(endCreated)));
            }

            //时间范围，大于等于某天
            if (StrUtil.isNotBlank(startCreated) && StrUtil.isBlank(endCreated)) {
                searchData.and().between("modified", new BetweenValue(DTUtil.toDateTime(startCreated), null, true, false));
            }

            //时间范围，小于等于某天
            if (StrUtil.isBlank(startCreated) && StrUtil.isNotBlank(endCreated)) {
                searchData.and().between("modified", new BetweenValue(null, DTUtil.toDateTime(endCreated), false, true));
            }
            if (StrUtil.isNotBlank(orderName)) {
                searchData.orderBy(orderName + " " + order);
            } else {
                searchData.orderBy("modified  desc");
            }
            PagerData<RecvFileData> datas = recvFileDataService.getPagerList(pager, searchData);
            model.addAttribute(DATA_KEY, datas.getDatas());
            model.addAttribute("localNode",localNode );
			model.addAttribute("send_node_list", recvFileDataService.getSendNodeList());
			if (isSysUser && recvFileDataService.getRecvNodeList().size()<=0) {
				model.addAttribute("recv_node_list", recvNodeList);
			}else{
				model.addAttribute("recv_node_list", recvFileDataService.getRecvNodeList());
			}
			
			if (isSysUser && recvFileDataService.getSendAdapterList().size()<=0) {
				model.addAttribute("send_adapter_list", recvAdapterList);
			}else{
				model.addAttribute("send_adapter_list", recvFileDataService.getSendAdapterList());
			}
			
			model.addAttribute("notify_status_list", AppConst.NotifyStatus.values());
            model.addAttribute("send_status_list", AppConst.SendStatus.values());
            setTotoal(model, datas.getTotal());
            return "monitor/recv_file_data_list";
        } catch (Exception e) {
            logger.error("操作失败", e);
            return toAlertPage(model, e.getMessage());
        }
    }

    /**
     * 根据nodecode获取sysinfoList
     *
     * @param sendNodecode
     * @return
     */
//    @RequestMapping(value = "/get_sysinfo_nodecode")
//    @ResponseBody
//    public Map<String, Object> getSysInfoByNodeCode(String sendNodecode) {
//        if (sendNodecode == null) {
//            return jsonSuccessDataResult("获取成功", null);
//        }
//        try {
//            NodeInfo nodeInfo = nodeInfoService.getNodeInfoByNodeCode(sendNodecode);
//            List<SysInfo> sysInfoList = sysInfoService.getSysInfoByNodeId(nodeInfo.getId());
//            return jsonSuccessDataResult("获取成功", sysInfoList);
//        } catch (Exception e) {
//            logger.error("获取失败", e);
//            return jsonFailResult("获取失败");
//        }
//    }

    /**
     * 查看页面
     *
     * @param model
     * @param id
     * @return
     */
	@RequestMapping(value = "/recv_file_data_get")
    public String get(Model model, String id) {
        try {
            RecvFileData vo = recvFileDataService.get(id);
            String payload = vo.getPayload();
            String path = AppConst.CMDATA_STORED_DIR + File.separator + payload;
            File file = new File(path);
            if (file.exists()) {
//                String payloadContent = FileUtils.readFileToString(file);
                //vo.setPayloadContent(payloadContent);
            } else {
                model.addAttribute("payloadError", "数据报文文件[" + path + "]不存在");
            }

            String routeLogXml = vo.getRoutelog();
            RouteLog routeLog = XstreamUtil.toObject(RouteLog.class,routeLogXml);
            model.addAttribute("netType", NodeInfoParam.NODE_NET_TYPE);
            model.addAttribute(DATA_KEY, vo);
            model.addAttribute("routeLog", routeLog);
            return "monitor/recv_file_data_get";
        } catch (Exception e) {
            logger.error("操作失败", e);
            return toAlertPage(model, e.getMessage());
        }
    }

    /**
     * 新增页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/recv_file_data_add")
    public String add(Model model) {
        try {
            return "monitor/recv_file_data_add";
        } catch (Exception e) {
            logger.error("操作失败", e);
            return toAlertPage(model, e.getMessage());
        }
    }

    /**
     * 根据ID删除记录
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/recv_file_data_delete", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> add(Model model, String id) {
        try {
            recvFileDataService.delete(id);
            return jsonSuccessResult("删除成功");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return jsonFailResult("删除失败");
        }
    }

    
    /**
     * 手动通知接收适配器，当通知接收 适配器失败的时候，才有这个功能 
     * @param id
     * @return
     */
	@RequestMapping(value = "/recv_file_data_notify_again")
    @ResponseBody
    public Map<String, Object> notifyAgain(String id){
    	String msg="";
    	try {
			RecvFileData fileData= recvFileDataService.get(id);
			fileData.setSendStatus(AppConst.SendStatus.REMOTE_READY.getStatus());
			recvFileDataService.update(fileData);
			return jsonSuccessResult("已经通知接收适配器!!!");
		} catch (Exception e) {
			 msg = "日志信息同步失败";
	         logger.error(msg, e);
	         return jsonFailResult(e.getMessage());
		}
    }
    
    /**
     * 路由信息同步，为了解决日志文件丢失，数据交换无法进行下去 
     * @param id
     * @return
     */
    @RequestMapping(value = "/recv_file_data_log_sync")
    @ResponseBody
    public Map<String, Object> logSync(String id){
    	String msg="";
    	try {
			RecvFileData fileData= recvFileDataService.get(id);
			File file =new File(AppConst.FILEDATA_GLOBALTOSENDRESP_DIR, fileData.getOrderId() + ".xml");
			if (!file.exists()) {//
				msg = "路由信息同步成功,请稍候刷新";
				XstreamUtil.toXmlfile(fileData, file);
				System.out.println("路由信息重新落地:"+file.getAbsolutePath());
				return jsonSuccessResult(msg);
			}else{
				msg = "路由信息不需要同步，该操作无效";
				return jsonFailResult(msg);
			}
			
		} catch (Exception e) {
			 msg = "路由信息同步失败";
	         logger.error(msg, e);
	         return jsonFailResult(e.getMessage());
		}
    }
    
    /**
     * 路由信息同步，为了解决日志文件丢失，数据交换无法进行下去 
     * @param id
     * @return
     */
    @RequestMapping(value = "/recv_file_data_receive")
    @ResponseBody
    public Map<String, Object> receive(String id){
    	String msg="";
    	try {
			RecvFileData fileData= recvFileDataService.get(id);
		   fileData.setSendStatus(AppConst.SendStatus.REMOTE_READY.value());//重置
		   RouteLog routeLog = XstreamUtil.toObject(RouteLog.class,fileData.getRoutelog());
		   routeLog.setRemoteSys(null);
		   fileData.setRoutelog(XstreamUtil.toXml(routeLog));
		   recvFileDataService.update(fileData);
		   return jsonSuccessResult("已通知适配器接收");
		} catch (Exception e) {
			 msg = "通知接收适配器接收失败";
	         logger.error(msg, e);
	         return jsonFailResult(e.getMessage());
		}
    }
    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/recv_file_data_deletes", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> deleteByIds(@RequestParam("ids") String ids) {
        String msg = "";
        try {
            msg = "删除成功";
            recvFileDataService.deleteBatchById(ids.split(","));
            return jsonSuccessResult(msg);
        } catch (Exception e) {
            msg = "删除系统信息失败";
            logger.error(msg, e);
            return jsonFailResult(e.getMessage());
        }
    }
}
